/**
 * 
 */
package cm.dpassyann.speedDating.controller.user;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cm.dpassyann.speedDating.model.user.bean.User;
import cm.dpassyann.speedDating.model.user.dao.IUserDao;

import com.google.gson.Gson;

/**
 * @author YDEOUNGO
 *
 */
@Controller
@RequestMapping("user/")
public class UserController {

	@Autowired
	private IUserDao userDao;

	@RequestMapping(value="add/")
	public String addUserHtml(HttpServletRequest request) {
		User user = new User();
		user.getParameter().setUsername(request.getParameter("username"));
		user.getParameter().setPassword(request.getParameter("password"));

		//.... lister le reste des pararamètres pour constituer un user
		userDao.addUser(user);

		return "/user/addConfirm";
	}

	@RequestMapping(value="add/{userJson}", method=RequestMethod.GET)
	public String addUser(@PathVariable String userJson, ModelMap model) {

		Gson gson = new Gson();
		User user = gson.fromJson(userJson, User.class);
		userDao.addUser(user);

		model.addAttribute("iduser", user.getId());

		return "/user/addConfirm";
	}

	@RequestMapping(value="all", method=RequestMethod.GET)
	public String getAllHtml(ModelMap model) {

		List<User> users= userDao.getAll();
		model.addAttribute("users", users);

		return "/user/userList";
	}

	/**
	 * 
	 * Méthode permettant de retourner un utilisateur depuis son identifiant 
	 * @param id de l'utilisateur
	 * @return
	 */
	@RequestMapping(value="{id}"/*,  headers="Accept=*//*"*/, method=RequestMethod.GET/*, produces="application/json"*/)
	public @ResponseBody User get(@PathVariable Long id) {
		User user = userDao.get(id);
		return user;
	}

	/**
	 * 
	 * Méthode permettant de lister tous les utilisateurs en base
	 * @return un flux json des différents utilisateurs en base
	 */
	@RequestMapping(value="", method=RequestMethod.GET)
	public  @ResponseBody List<User> getAll() {

		List<User> users= userDao.getAll();

		return users;
	}

	@RequestMapping(value="connexion/{login}/{password}", method=RequestMethod.GET)
	public @ResponseBody User connection(
			@PathVariable(value="login") String login,
			@PathVariable(value="password") String password
			) {
		User user = userDao.isExist(login, password);
		return user;
	}

}
